import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export interface TabItem {
  path: string
  title: string
  icon: string
  closable?: boolean
  query?: Record<string, any>
  params?: Record<string, any>
}

export const useTabsStore = defineStore('tabs', () => {
  // 状态
  const tabs = ref<TabItem[]>([])
  const activeTab = ref('')

  // 计算属性
  const hasTabs = computed(() => tabs.value.length > 0)
  const currentTab = computed(() => tabs.value.find(tab => tab.path === activeTab.value))

  // 方法
  const addTab = (tab: TabItem) => {
    // 检查是否已存在
    const existingTab = tabs.value.find(t => t.path === tab.path)
    if (!existingTab) {
      tabs.value.push({
        ...tab,
        closable: tab.closable !== false // 默认可关闭
      })
    }
    activeTab.value = tab.path
  }

  const removeTab = (path: string) => {
    const index = tabs.value.findIndex(tab => tab.path === path)
    if (index > -1) {
      tabs.value.splice(index, 1)
      
      // 如果删除的是当前激活的标签页，需要切换到其他标签页
      if (activeTab.value === path) {
        if (tabs.value.length > 0) {
          // 优先选择前一个标签页，如果没有则选择后一个
          const newIndex = index > 0 ? index - 1 : 0
          activeTab.value = tabs.value[newIndex].path
        } else {
          activeTab.value = ''
        }
      }
    }
  }

  const closeTab = (path: string) => {
    // 不能关闭最后一个标签页
    if (tabs.value.length <= 1) {
      return
    }
    removeTab(path)
  }

  const closeOtherTabs = (currentPath: string) => {
    tabs.value = tabs.value.filter(tab => tab.path === currentPath)
    activeTab.value = currentPath
  }

  const closeAllTabs = () => {
    tabs.value = []
    activeTab.value = ''
  }

  const setActiveTab = (path: string) => {
    const tab = tabs.value.find(t => t.path === path)
    if (tab) {
      activeTab.value = path
    }
  }

  const updateTab = (path: string, updates: Partial<TabItem>) => {
    const tab = tabs.value.find(t => t.path === path)
    if (tab) {
      Object.assign(tab, updates)
    }
  }

  const clearTabs = () => {
    tabs.value = []
    activeTab.value = ''
  }

  // 初始化首页标签
  const initHomeTab = () => {
    if (tabs.value.length === 0) {
      addTab({
        path: '/',
        title: '首页',
        icon: 'House',
        closable: false
      })
    }
  }

  return {
    // 状态
    tabs,
    activeTab,
    
    // 计算属性
    hasTabs,
    currentTab,
    
    // 方法
    addTab,
    removeTab,
    closeTab,
    closeOtherTabs,
    closeAllTabs,
    setActiveTab,
    updateTab,
    clearTabs,
    initHomeTab
  }
})
